//
//  YuYinBoFangView.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/29.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "YuYinBoFangView.h"

@implementation YuYinBoFangView
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (void)awakeFromNib{
    [super awakeFromNib];
    self.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:9/255.0 blue:86/255.0 alpha:0.1600].CGColor;
    self.layer.shadowOffset = CGSizeMake(0,0);
    self.layer.shadowOpacity = 1;
    self.layer.shadowRadius = 5;
    
    [_mainSlider setThumbImage:LocalImagePath(@"进度条原点") forState:UIControlStateNormal];
    
    
    [self initDFPlayer];
    
    
}
- (NSArray<DFPlayerModel *> *)df_audioDataForPlayer:(DFPlayer *)player{
    NSMutableArray *array = [NSMutableArray array];
    DFPlayerModel *model        = [[DFPlayerModel alloc] init];
    model.audioId               = 0;//****重要。AudioId从0开始，仅标识当前音频在数组中的位置。
    model.audioUrl  = [NSURL URLWithString:_voiceUrl];
    [array addObject:model];
    return array;
}

- (void)setVoiceUrl:(NSString *)voiceUrl{
    _voiceUrl = voiceUrl;
    
    
    [self initDFPlayer];
}


#pragma mark - DFPLayer dataSource

#pragma mark - DFPlayer delegate

//改变播放进度
- (IBAction)gaiBianJinDu:(UISlider *)sender {
    CGFloat time = [DFPlayer sharedPlayer].totalTime * sender.value;
    
    [[DFPlayer sharedPlayer] df_seekToTime:time completionBlock:^{
        _playButton.selected = NO;
    }];
    
}
#pragma mark - 初始化DFPlayer
- (void)initDFPlayer{
    if([DFPlayer sharedPlayer] != nil){
        [[DFPlayer sharedPlayer] df_deallocPlayer];
    }
    
    [[DFPlayer sharedPlayer] df_initPlayerWithUserId:@"001"];
    [DFPlayer sharedPlayer].dataSource  = self;
    [DFPlayer sharedPlayer].delegate    = self;
    [DFPlayer sharedPlayer].category    = AVAudioSessionCategoryPlayback;
    [DFPlayer sharedPlayer].isObserveWWAN = YES;
    
    [[DFPlayer sharedPlayer] df_reloadData];
    
    [[DFPlayer sharedPlayer] df_playWithAudioId:0];
    [[DFPlayer sharedPlayer] df_play];
}

//播放进度代理
- (void)df_player:(DFPlayer *)player progress:(CGFloat)progress currentTime:(CGFloat)currentTime{
    _mainSlider.value = progress;
    _dangQianTimeLabel.text = [self timeFormatted:currentTime];
    _quanBuTimeLabel.text = [self timeFormatted:[DFPlayer sharedPlayer].totalTime];
}


- (NSString *)timeFormatted:(int)totalSeconds
{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    if (hours > 0) {
        return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02d:%02d",minutes, seconds];
}

- (void)df_playerDidPlayToEndTime:(DFPlayer *)player{
    [[DFPlayer sharedPlayer] df_playWithAudioId:0];
}

//状态信息代理
- (void)df_player:(DFPlayer *)player didGetStatusCode:(DFPlayerStatusCode)statusCode{
    
    if (statusCode == DFPlayerStatusFailed) {
        [ZZPUtils showWarning:@"该音频无法播放"];
        return;
    }else if(statusCode == DFPlayerStatusTimeOut){
        [ZZPUtils showWarning:@"网络请求超时请稍后再试"];
        return;
    }else if(statusCode == 2){
        [SMGlobalMethod showViewCenterWithMessage:@"请求超时"];
    }else if(statusCode == 8){
        return;
    }
}
//播放或者暂停
- (IBAction)boFang:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.selected){
        [[DFPlayer sharedPlayer] df_pause];
    }else{
        [[DFPlayer sharedPlayer] df_play];
    }
}

//关闭
- (IBAction)guanBi:(UIButton *)sender {
    [[DFPlayer sharedPlayer] df_deallocPlayer];
    self.hidden = YES;
}
//倍速
- (IBAction)beiSu:(UIButton *)sender {
    SPAlertController *alertController = [SPAlertController alertControllerWithTitle:nil message:nil preferredStyle:SPAlertControllerStyleActionSheet];
    SPAlertAction *action1 = [SPAlertAction actionWithTitle:@"1.0倍" style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
         //拍照
        [[DFPlayer sharedPlayer] df_setRate:1.0];
    }];
    [alertController addAction:action1];
    action1.titleColor = mainFontColor;
    action1.titleFont = [UIFont systemFontOfSize:17];
    SPAlertAction *action2 = [SPAlertAction actionWithTitle:@"1.5倍" style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
        //相册
        [[DFPlayer sharedPlayer] df_setRate:1.5];
    }];
    [alertController addAction:action2];
    action2.titleColor = mainFontColor;
    action2.titleFont = [UIFont systemFontOfSize:17];
    SPAlertAction *cancel = [SPAlertAction actionWithTitle:@"取消" style:SPAlertActionStyleCancel handler:^(SPAlertAction * _Nonnull action) {
    }];
    [alertController addAction:cancel];
    cancel.titleColor = mainFontColor;
    cancel.titleFont = [UIFont systemFontOfSize:17];
    [[ZZPUtils activityViewController] presentViewController:alertController animated:YES completion:nil];
}

//下载
- (IBAction)xiaZai:(UIButton *)sender {
    
    [self downLoadWithFilePath:_voiceUrl];
}
#pragma mark - 下载文件

- (void)downLoadWithFilePath:(NSString *)filePath {
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 11) {
        
    } else {
        [ZZPUtils showWarning:@"下载文件要求手机系统版本在11.0以上"];
        return;
    }
    [[ZZPRequest getWebUtil] addAnimation];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest * request) {
        request.url =  filePath;
        request.methodType=ZBMethodTypeDownLoad;
        request.downloadState=ZBDownloadStateStart;//开始 //ZBDownloadStateStop暂停
    } progress:^(NSProgress * _Nullable progress) {
        NSLog(@"onProgress: %.2f", 100.f * progress.completedUnitCount/progress.totalUnitCount);
    } success:^(id  responseObject,ZBURLRequest * request) {
        NSLog(@"ZBMethodTypeDownLoad 此时会返回存储路径文件: %@", responseObject);
        
        [[ZZPRequest getWebUtil] hiddenAnimation];
        
        //在任何地方拿到下载文件
        NSString *file=[ZBRequestManager getDownloadFileForKey:request.url];
        
        NSLog(@"file:%@",file)
        
        UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:file] inMode:UIDocumentPickerModeExportToService];
        // 设置代理
        documentPickerVC.delegate = self;
        // 设置模态弹出方式
        documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
        [[ZZPUtils activityViewController] presentViewController:documentPickerVC animated:YES completion:nil];
        
    } failure:^(NSError * _Nullable error) {
        NSLog(@"error: %@", error);
        
        [[ZZPRequest getWebUtil] hiddenAnimation];
    }];
}



#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            // 读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                // 读取出错
            } else {
                // 上传
                NSLog(@"fileName : %@", fileName);
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授权失败
    }
}


- (void)closeVoice{
    [[DFPlayer sharedPlayer] df_deallocPlayer];
}
@end
